package com.example.demo.jucConcurrent.CountDownLatch详解;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch代替 wait notify 好处是通讯方式简单,不涉及锁,count值为0时当前线程继续执行
 */
public class T3 {

    volatile List list = new ArrayList();

    public  void add(int i){
        list.add(i);
    }

    public  int getSize(){
        return  list.size();
    }

    public static void main(String[] args) {
        T3 t3 = new T3();
        CountDownLatch countDownLatch = new CountDownLatch(1);

        new Thread(()->{
            System.out.println("t2 START");
            if(t3.getSize()!=5){

                try {
                    countDownLatch.await();
                    System.out.println("t2 end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2").start();


        new Thread(()->{
            System.out.println("t1 start");
            for (int i = 0; i <9 ; i++) {
                t3.add(i);
                System.out.println("add"+i);
                if(t3.getSize() == 5){
                    System.out.println("Count is  open");
                    countDownLatch.countDown();
                }
            }
            System.out.println("t1 end");
        },"t1").start();
    }
}
